package com.web.filter;

import org.apache.commons.lang.StringUtils;
import org.sitemesh.builder.SiteMeshFilterBuilder;
import org.sitemesh.config.ConfigurableSiteMeshFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


public class SiteMeshFilter extends ConfigurableSiteMeshFilter {
    private static final String FRONTEND_DECORATOR_PAGE = "/WEB-INF/views/decorator/frontend.jsp";
    private static final String BACKEND_DECORATOR_PAGE = "/WEB-INF/views/decorator/backend.jsp";
    private static final String EMPTY_DECORATOR_PAGE = "/WEB-INF/views/decorator/empty.jsp";

    private String excludedPages;
    private String[] excludedPageArray;

    @Override
    protected void applyCustomConfiguration(SiteMeshFilterBuilder builder) {
        //frontend decorator
        builder.addDecoratorPath("/", FRONTEND_DECORATOR_PAGE);
        builder.addDecoratorPath("/index*", FRONTEND_DECORATOR_PAGE);
        builder.addDecoratorPath("/angular", FRONTEND_DECORATOR_PAGE);
        builder.addDecoratorPath("/qrcode", FRONTEND_DECORATOR_PAGE);
        builder.addDecoratorPath("/work*", FRONTEND_DECORATOR_PAGE);

        //backend decorator
        builder.addDecoratorPath("/admin*", BACKEND_DECORATOR_PAGE);
        builder.addDecoratorPath("/role*", BACKEND_DECORATOR_PAGE);
        builder.addDecoratorPath("/back*", BACKEND_DECORATOR_PAGE);

        //empty decorator
        builder.addDecoratorPath("/index/first", EMPTY_DECORATOR_PAGE);
        builder.addDecoratorPath("/index/second", EMPTY_DECORATOR_PAGE);
        builder.addDecoratorPath("/index/third", EMPTY_DECORATOR_PAGE);

        //customer decorator
        builder.addTagRuleBundle(new ExtHtmlTagRuleBundle());

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        excludedPages = filterConfig.getInitParameter("excludedPages");
        if (StringUtils.isNotEmpty(excludedPages)) {
            excludedPageArray = excludedPages.split(",");
        }
        super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        boolean isExcludedPage = false;
        //判断是否在过滤url之外
        for (String page : excludedPageArray) {
            if (((HttpServletRequest) servletRequest).getServletPath().equals(page)) {
                isExcludedPage = true;
                break;
            }
        }
        if (isExcludedPage) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            super.doFilter(servletRequest, servletResponse, filterChain);
        }
    }
}
